#include <iostream>
#include <cstdlib>
#include <string>
#include <cstring>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "err.hpp"
#include <pthread.h>

void usage()
{
    std::cout << "usage:\n\t" << "./udp_client server_ip server_port\n" << std::endl; 
}

void* Recv(void* args)
{
    int sock = *(static_cast<int*>(args));
    while(true)
    {
        char buffer[1024];
        sockaddr_in tmp;
        socklen_t len = sizeof(tmp);
        // 打印结果
        int n = recvfrom(sock, buffer, sizeof(buffer)-1, 0, (sockaddr*)&tmp, &len);
        if(n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

int main(int argc, char* argv[])
{
    // 客户端的绑定问题 防止端口号冲突
    // 本地环回
    if(argc != 3)
    {
        usage();
        exit(USAGE_ERR);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        std::cerr << "create socket error: " << strerror(errno) << std::endl;
        exit(SOCK_ERR);
    }

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    pthread_t recv;
    pthread_create(&recv, nullptr, &Recv, &sock);

    while(true)
    {
        std::string command;
        std::cerr << "Please enter message# ";
        std::getline(std::cin, command);
        // 发送指令
        sendto(sock, command.c_str(), command.size(), 0, (sockaddr*)&server, sizeof(server));
    }

    return 0;
}